package kr.co.redcircle.broker.io.net.Unicast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import kr.co.redcircle.broker.Broker;
import kr.co.redcircle.broker.registry.Registry;
import kr.co.redcircle.broker.security.KeyCollection;
import net.sf.json.JSONObject;

public class SyncHostCallHandler {

	private JSONObject request = null;
	private boolean sFlag;
	
	public SyncHostCallHandler(JSONObject requestString, boolean secureFlag) {
		this.request = requestString;
		this.sFlag = secureFlag;
	}

	public String run() {
		
		String responseString = null;
		
		if (this.request != null){
			synchronized (request) {
				
				Socket clientSocket;
				
				String hostString = this.request.getString(Broker.HOST);
				Integer portInt = (Integer) this.request.get(Broker.PORT);
				String requestString = request.toString();  
				 
				System.out.println("SyncHostCallHandler.run.host : " + hostString);
				System.out.println("SyncHostCallHandler.run.port : " + portInt);
				System.out.println("SyncHostCallHandler.run.request : " + requestString);
				
				try {
					if (this.sFlag){
						KeyCollection kCollection = Registry.getKeyCollection();
						SSLContext ctx = SSLContext.getInstance("TLS");
						ctx.init(kCollection.getKeyManagers(), kCollection.getTrustManagers(), null);

						SSLSocketFactory sslsocketfactory = ctx.getSocketFactory();
						clientSocket = sslsocketfactory.createSocket(hostString, portInt);						
					}else{
						clientSocket = new Socket(hostString, portInt);
					}
					PrintWriter requestWriter = new PrintWriter(clientSocket.getOutputStream(), true);
					BufferedReader requestReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
					requestWriter.write(requestString + Broker.LINE_DIV);
					requestWriter.flush();
					
					responseString = requestReader.readLine();
					
			    	requestReader.close();
				    requestWriter.close();
				    clientSocket.close();		

					System.out.println("SyncHostCallHandler.run.response : " + responseString);
				    
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
				} catch (KeyManagementException e) {
					e.printStackTrace();
				}
				
			}
		}	
		
		return responseString;
	}

}
